/**
 * src/tools/base.ts
 * 工具系统基础架构 - 单一数据源设计
 */

import type { ToolResult, ToolDefinition, ToolParameter } from '../types/types';

/**
 * 工具处理器接口
 */
export interface ToolHandler {
    execute(args: Record<string, any>, callId: string): Promise<ToolResult>;
    getDefinition(): ToolDefinition;
    getId(): string;
}

/**
 * 抽象工具基类
 * 所有具体工具都继承此类，实现逻辑与定义的统一管理
 */
export abstract class AbstractTool implements ToolHandler {
    // 1. 核心元数据 (由子类实现)
    abstract readonly id: string;
    abstract readonly name: string;
    abstract readonly description: string;
    abstract readonly icon: string;
    
    // 2. 行为配置
    protected readonly requireConfirm: boolean = true;
    protected readonly enabled: boolean = true;

    /**
     * 获取工具参数定义 (由子类实现)
     * 用于生成 UI 表单和验证输入
     */
    protected abstract getParameters(): ToolParameter[];

    /**
     * 执行逻辑 (由子类实现)
     */
    abstract execute(args: Record<string, any>, callId: string): Promise<ToolResult>;

    /**
     * 获取工具的完整定义 (供 UI 和系统使用)
     * 自动组装元数据和参数
     */
    getDefinition(): ToolDefinition {
        return {
            id: this.id,
            name: this.name,
            description: this.description,
            icon: this.icon,
            requireConfirm: this.requireConfirm,
            enabled: this.enabled,
            parameters: this.getParameters()
        };
    }

    getId(): string {
        return this.id;
    }

    /**
     * 辅助方法：创建成功结果
     */
    protected createSuccessResult(callId: string, output: string, duration: number, exitCode?: number): ToolResult {
        return {
            callId,
            success: true,
            output,
            duration,
            exitCode
        };
    }

    /**
     * 辅助方法：创建失败结果
     */
    protected createErrorResult(callId: string, error: string, duration: number): ToolResult {
        return {
            callId,
            success: false,
            error,
            duration
        };
    }
}